package tencent

import (
	"basic-go/syntax/webook/pkg/limiter"
	"context"
	"errors"
	"fmt"
	"github.com/ecodeclub/ekit"
	"github.com/ecodeclub/ekit/slice"
	sms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111"
)

const key = "sms-limiter"

var errLimited = errors.New("触发限流")

type Service2 struct {
	client   *sms.Client
	appId    *string
	signName *string
	limiter  limiter.Limiter
}

func NewService2(client *sms.Client, appId string, signName string, limiter limiter.Limiter) *Service2 {
	return &Service2{
		client:   client,
		appId:    ekit.ToPtr(appId),
		signName: ekit.ToPtr(signName),
		limiter:  limiter,
	}
}

func (s *Service2) Send2(ctx context.Context, tpl string, args []string, numbers ...string) error {
	// 加上限流判断
	ok, err := s.limiter.Limit(ctx, key)
	if err != nil {
		return fmt.Errorf("短信服务判断是否限流异常 %w", err)
	}
	if ok {
		return errLimited
	}

	req := sms.NewSendSmsRequest()
	req.PhoneNumberSet = toStringPtrSlice(numbers)
	req.SmsSdkAppId = s.appId
	req.SetContext(ctx)
	req.TemplateParamSet = toStringPtrSlice2(args)
	req.TemplateId = ekit.ToPtr[string](tpl)
	req.SignName = s.signName
	resp, err := s.client.SendSms(req)
	if err != nil {
		return err
	}
	for _, status := range resp.Response.SendStatusSet {
		if status.Code == nil || *(status.Code) != "Ok" {
			return fmt.Errorf("发送失败，code: %s, 原因： %s",
				*status.Code, *status.Message)
		}
	}
	return nil
}

func toStringPtrSlice2(data []string) []*string {
	return slice.Map[string, *string](data,
		func(idx int, src string) *string {
			return &src
		})
}
